package com.jiangfan.tank;

import java.awt.*;

public class Bullet {
    private static final int SPEED = 10;

    private boolean live = true;
    TankFrame tf = null;

    private int x, y;

    private Dir dir;

    public static int WIDTH = ResourceMgr.bulletD.getWidth();
    public static int HEIGHT = ResourceMgr.bulletD.getHeight();

    private Group group = Group.Enemy;

    Rectangle rect = new Rectangle();

    public Bullet(int x, int y, Dir dir, Group group, TankFrame tf){
        this.x = x;
        this.y = y;
        this.dir = dir;
        this.group = group;
        this.tf = tf;

        rect.x = this.x;
        rect.y = this.y;
        rect.width = WIDTH;
        rect.height = HEIGHT;
    }

    public void paint(Graphics g){
        if(!live) {
            tf.bullets.remove(this);
        }

        Color c = g.getColor();
        g.setColor(Color.RED);
        // 调整设置子弹出现的位置
        switch (dir) {
            case LEFT:
                g.drawImage(ResourceMgr.bulletL, x, y, null);
                break;
            case RIGHT:
                g.drawImage(ResourceMgr.bulletR, x, y, null);
                break;
            case UP:
                g.drawImage(ResourceMgr.bulletU, x, y, null);
                break;
            case DOWN:
                g.drawImage(ResourceMgr.bulletD, x, y, null);
                break;
        }

        g.setColor(c);

        move();
    }

    public void move(){
        switch (dir){
        case LEFT:
            x -= SPEED;
            break;

        case RIGHT:
            x += SPEED;
            break;

        case UP:
            y -= SPEED;
            break;

        case DOWN:
            y += SPEED;
            break;
        }

        //update rect
        rect.x = this.x;
        rect.y = this.y;

        if(x < 0 || y < 0 || x > TankFrame.GAME_WIDTH || y > TankFrame.GAME_HEIGHT) live = false;
    }

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }

    public Group getGroup() {
        return group;
    }

    public void setGroup(Group group) {
        this.group = group;
    }

    public void collideWith(Tank tank) {
        if (this.group == tank.getGroup()) return;

        if(rect.intersects(tank.rect)) { // rect1和rect2有相交的部分
            tank.die();
            this.die();
            int eX = tank.getX() + Tank.WIDTH/2 - Explosion.WIDTH/2;
            int eY = tank.getY() + Tank.HEIGHT/2 - Explosion.HEIGHT/2;
            tf.explosions.add(new Explosion(eX, eY, tf));
        }
    }

    private void die() {
        this.live = false;
    }
}
